package com.bzs.huwei.huweitest;

import lombok.val;

import java.math.BigDecimal;
import java.util.Stack;

class Test {
    public static void main(String[] args) {
        //要计算的公式
        //认为公式为正确的不需要校验
        //
        //sum(1,sum(1,1))
        //ifn(3+6<2,ifn(9+avg(3,1,sum(8,3)-sum(2,4),7)*3+8/2>0,3,8),9)
        //String equation = "sum(1+sum(sum(1,1),1),1)";//19
        //ifn(sum(1,1,1,1)>0,1,0)
        //sum(1,sum(1,1))
        //ifn(3+6<2,ifn(9+avg(3,1,sum(1,3)-sum(2,4),7)*3+8/2>0,3,8),9)
        String equation = "ifn(3+6<2,ifn(9+avg(3,1,sum(1,3)-sum(2,4),7)*3+8/2>0,3,8),9)+sum(1,9)";//19
        //定义公式解析器
        //传入运算函数所在的类
        Calculator calculator = new Calculator(Test.class);
        //添加计算方法
        //求和
        calculator.addFunction("sum");
        //求平均值
        calculator.addFunction("avg");
        //if函数规则
        calculator.addFunction("ifn");
        //计算值
        BigDecimal result = calculator.calculate(equation);
        System.out.println(result);
        //val getcountofbrac = getcountofbrac("ifn(3+6<2,ifn(9+avg(3,1,sum(1,3)-sum(2,4),7)*3+8/2>0,3,8),9)");
        //System.out.println("getcountofbrac = " + getcountofbrac);

    }


    public static String getcountofbrac(String expression) {
        int secondLeftBracketIndex = expression.indexOf('(', expression.indexOf('(') + 1);
        int secondLastRightBracketIndex = expression.lastIndexOf(')', expression.lastIndexOf(')') - 1);

        if (secondLeftBracketIndex == -1 || secondLastRightBracketIndex == -1 || secondLeftBracketIndex >= secondLastRightBracketIndex) {
            // 找不到第二个左括号或第二个右括号，或者左括号在右括号之后，返回空字符串或原始表达式
            return "";
        }

        String result = expression.substring(secondLeftBracketIndex, secondLastRightBracketIndex + 1);
        return result;
    }

    Test() {
    }

    /**
     * 求和
     *
     * @param stack
     * @return
     */
    public static BigDecimal sum(Stack stack) {
        BigDecimal sum = new BigDecimal("0");
        while (!stack.isEmpty()) {
            sum = sum.add(new BigDecimal(stack.pop().toString()));
        }
        return sum;
    }

    /**
     * 求平均值
     *
     * @param stack
     * @return
     */
    public static BigDecimal avg(Stack stack) {
        BigDecimal sum = new BigDecimal("0");
        int count = stack.size();
        while (!stack.isEmpty()) {
            sum = sum.add(new BigDecimal(stack.pop().toString()));
        }
        return sum.divide(new BigDecimal(count), 7, BigDecimal.ROUND_HALF_UP);
    }

    public static BigDecimal ifn(Stack stack) {
        //如果前面为假->(X>0 返回 0) ，将3弹出 返回 8
        if (stack.pop().toString().equals("0")) {
            stack.pop();
        }
        //如果前面为真->(X>0 返回 1) ，返回3
        return new BigDecimal(stack.pop().toString());
    }

}
